import traceback

from src.utils.serial_communication import SerialCommunication
import time

class SwitchControl:
    ON_COMMAND = bytes.fromhex('010600000001480A')
    OFF_COMMAND = bytes.fromhex('01060000000089CA')
    STATUS_COMMAND = bytes.fromhex('01040000000131CA')

    def __init__(self, port='COM14', baudrate=38400, timeout=1):
        self.serial_com = SerialCommunication(port=port, baudrate=baudrate, timeout=timeout)
        print("SwitchControl initialized with SerialCommunication.")

    def turn_on(self):
        print("Sending ON command...")
        self.serial_com.send_data(self.ON_COMMAND)

    def turn_off(self):
        print("Sending OFF command...")
        self.serial_com.send_data(self.OFF_COMMAND)

    def get_status(self):
        print("Sending STATUS command...")
        self.serial_com.send_data(self.STATUS_COMMAND)

    def close(self):
        self.serial_com.close()


# 使用示例
if __name__ == "__main__":
    switch_control = SwitchControl(port="COM14", baudrate=38400)
    try:
        switch_control.turn_on()  # 发送开启命令
        time.sleep(1)
        switch_control.get_status()  # 查询开关状态
        time.sleep(1)
        switch_control.turn_off()  # 发送关闭命令
        time.sleep(1)
        switch_control.get_status()  # 再次查询状态
    except Exception as e:
        print(e)
    finally:
        switch_control.close()  # 关闭串口